import React, { useState, useCallback } from 'react';
import { Upload, FileText, AlertCircle, CheckCircle } from 'lucide-react';
import axios from 'axios';
import { API_CONFIG, getApiUrl } from '../config/api';

interface UploadStatus {
  status: 'idle' | 'uploading' | 'success' | 'error';
  message?: string;
}

const DocumentUpload: React.FC = () => {
  const [dragOver, setDragOver] = useState(false);
  const [uploadStatus, setUploadStatus] = useState<UploadStatus>({ status: 'idle' });
  const [uploadedFiles, setUploadedFiles] = useState<string[]>([]);

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setDragOver(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setDragOver(false);
  }, []);

  const validateFile = (file: File): string | null => {
    // 检查文件类型
    const allowedTypes = ['application/pdf', 'text/markdown', 'text/plain'];
    const allowedExtensions = ['.pdf', '.md', '.txt'];
    const hasValidType = allowedTypes.includes(file.type);
    const hasValidExtension = allowedExtensions.some(ext => file.name.toLowerCase().endsWith(ext));
    
    if (!hasValidType && !hasValidExtension) {
      return '只支持 PDF 和 Markdown 文件';
    }

    // 检查文件大小 (10MB)
    if (file.size > 10 * 1024 * 1024) {
      return '文件大小不能超过 10MB';
    }

    return null;
  };

  const uploadFile = async (file: File) => {
    const validationError = validateFile(file);
    if (validationError) {
      setUploadStatus({ status: 'error', message: validationError });
      return;
    }

    setUploadStatus({ status: 'uploading', message: '正在上传文档...' });

    try {
      const formData = new FormData();
      formData.append('file', file);

      // 使用原生fetch而不是axios，以便更好地控制请求格式
      const response = await fetch(getApiUrl(API_CONFIG.ENDPOINTS.UPLOAD_DOCUMENT), {
        method: 'POST',
        body: formData,
        // 不设置Content-Type头，让浏览器自动设置boundary
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const result = await response.text();

      setUploadStatus({ status: 'success', message: `${file.name} 上传成功` });
      setUploadedFiles(prev => [...prev, file.name]);
      
    } catch (error) {
      console.error('文档上传失败:', error);
      setUploadStatus({ 
        status: 'error', 
        message: axios.isAxiosError(error) 
          ? `上传失败: ${error.response?.data || error.message}`
          : '上传失败，请重试'
      });
    }
  };

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setDragOver(false);

    const files = Array.from(e.dataTransfer.files);
    if (files.length > 0) {
      uploadFile(files[0]);
    }
  }, []);

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (files && files.length > 0) {
      uploadFile(files[0]);
    }
    // 清空 input 值，允许重复选择同一文件
    e.target.value = '';
  };

  return (
    <div className="max-w-2xl mx-auto p-6">
      <div className="mb-6">
        <h2 className="text-2xl font-bold text-gray-900 mb-2">文档上传</h2>
        <p className="text-gray-600">
          上传 PDF 或 Markdown 文档以创建知识库，支持 RAG 问答
        </p>
      </div>

      {/* 拖拽上传区域 */}
      <div
        className={`
          relative border-2 border-dashed rounded-lg p-8 text-center transition-colors
          ${dragOver 
            ? 'border-blue-400 bg-blue-50' 
            : 'border-gray-300 hover:border-gray-400'
          }
        `}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
      >
        <input
          type="file"
          onChange={handleFileSelect}
          accept=".pdf,.md,.txt"
          className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
          disabled={uploadStatus.status === 'uploading'}
        />
        
        <div className="space-y-4">
          <div className="flex justify-center">
            <Upload className={`w-12 h-12 ${dragOver ? 'text-blue-500' : 'text-gray-400'}`} />
          </div>
          
          <div>
            <p className="text-lg text-gray-900">
              拖拽文件到此处，或 <span className="text-blue-600 font-medium">点击选择文件</span>
            </p>
            <p className="text-sm text-gray-500 mt-2">
              支持 PDF、Markdown 文件，最大 10MB
            </p>
          </div>
        </div>
      </div>

      {/* 上传状态 */}
      {uploadStatus.status !== 'idle' && (
        <div className={`
          mt-4 p-4 rounded-lg flex items-center space-x-3
          ${uploadStatus.status === 'uploading' ? 'bg-blue-50 text-blue-700' : ''}
          ${uploadStatus.status === 'success' ? 'bg-green-50 text-green-700' : ''}
          ${uploadStatus.status === 'error' ? 'bg-red-50 text-red-700' : ''}
        `}>
          {uploadStatus.status === 'uploading' && (
            <>
              <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-blue-600"></div>
              <span>{uploadStatus.message}</span>
            </>
          )}
          {uploadStatus.status === 'success' && (
            <>
              <CheckCircle className="w-5 h-5" />
              <span>{uploadStatus.message}</span>
            </>
          )}
          {uploadStatus.status === 'error' && (
            <>
              <AlertCircle className="w-5 h-5" />
              <span>{uploadStatus.message}</span>
            </>
          )}
        </div>
      )}

      {/* 已上传文件列表 */}
      {uploadedFiles.length > 0 && (
        <div className="mt-6">
          <h3 className="text-lg font-medium text-gray-900 mb-3">已上传文档</h3>
          <div className="space-y-2">
            {uploadedFiles.map((filename, index) => (
              <div key={index} className="flex items-center space-x-3 p-3 bg-gray-50 rounded-lg">
                <FileText className="w-5 h-5 text-gray-500" />
                <span className="text-gray-700">{filename}</span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default DocumentUpload; 